package com.example.onlineeducation.ui.common

import android.Manifest
import android.annotation.TargetApi
import android.os.Build
import androidx.annotation.RequiresApi
import com.example.onlineeducation.R
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.data.constant.Constants
import com.example.onlineeducation.data.json.VersionJson
import com.example.onlineeducation.databinding.WelcomeAcBinding
import com.example.onlineeducation.ui.auth.LoginActivity
import com.example.onlineeducation.viewmodel.WelcomeVM
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.yc.jetpacklib.download.YcDownload
import com.yc.jetpacklib.extension.ycToNoEmpty
import com.yc.jetpacklib.net.doFail
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.permission.YcPermissionHelper
import com.yc.jetpacklib.utils.YcInstallUtil
import com.yc.jetpacklib.utils.YcVersionUtil
import com.yc.jetpacklib.widget.dialog.YcCommonDialog
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay

/**
 * Creator: yc
 * Date: 2022/4/1 15:10
 * UseDes:
 */

class WelcomeAc : BaseActivity<WelcomeAcBinding>(WelcomeAcBinding::inflate) {
    private val mViewModel: WelcomeVM by ycViewModels()
    private var mNextActivityJob: Job? = null//延迟跳转到下个页面的句柄
    private val mYcInstallUtil = YcInstallUtil(this)

    /**
     * 读写权限
     */
    fun getExternalStorage(): List<String> = listOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,  //存储卡写权限
        Manifest.permission.WRITE_EXTERNAL_STORAGE,  //存储卡读权限
    )

    /**
     * 定位权限
     */
    fun getLocationPermission(): List<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        listOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.ACCESS_BACKGROUND_LOCATION
        )
    } else {
        listOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
    }


    private val mYcPermissionHelper: YcPermissionHelper by lazy {
        YcPermissionHelper(this).apply {
            val permission: MutableList<String> = mutableListOf()
            permission.addAll(getExternalStorage())
            permission.addAll(getLocationPermission())
            mPermission = permission.toTypedArray()
            mSuccessCall = {
                mViewModel.checkVersion()
            }
        }
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .statusBarColor(R.color.transparent)
            .statusBarDarkFont(false)
            .hideBar(BarHide.FLAG_SHOW_BAR)
            .fitsSystemWindows(false)
            .init()
    }

    override fun WelcomeAcBinding.initView() {
        mViewModel.mVersionResult.observe {
            it.doSuccess { data ->
                checkVersion(data)
            }.doFail { error ->
                mDialog.apply {
                    setMsg(error.msg)
                    setLeftBtnText("重试")
                    setOnLeftClick { mViewModel.checkVersion() }
                    setRightBtnText("跳过")
                    setOnRightClick { toNextActivity(0) }
                }.show()
            }
        }

        mYcPermissionHelper.startOnCreate()
    }

    /**
     * 监测apk版本
     * @param data VersionJson
     */
    private fun checkVersion(data: VersionJson) {
        if (data.versionName == null || data.versionName <= YcVersionUtil.getVersionCode(this)) {
            toNextActivity(2000)
        } else {
            if (data.isForce) {//是否强制更新
                downApk(data.downloadUrl)
            } else {
                mDialog.setMsg(data.description)
                    .setRightBtnText("更新")
                    .setOnRightClick {
                        downApk(data.downloadUrl)
                    }.setLeftBtnText("跳过")
                    .setOnLeftClick {
                        toNextActivity(0)
                    }.show()
            }
        }
    }

    /**
     * 下载apk
     * @param apkUrl String?
     */
    private fun downApk(apkUrl: String?) {
        if (apkUrl == null) {
            mDialog.setMsg("下载地址为空")
                .setLeftBtnText("退出")
                .setOnLeftClick { finish() }
                .setRightBtnText("重试")
                .setOnRightClick { mViewModel.checkVersion() }
                .show()
        } else {
            YcDownload.createDownloadApkHasProgress(this, apkUrl, Constants.apkPath(), onSuccess = {
                mYcInstallUtil.mApkFile = it
                mYcInstallUtil.installApk()
            }, onFail = {
                mDialog.setMsg(it.ycToNoEmpty("下载失败"))
                    .setLeftBtnText("跳过")
                    .setOnLeftClick { toNextActivity(0) }
                    .setRightBtnText("重试")
                    .setOnRightClick { mViewModel.checkVersion() }
                    .show()
            }).start()
        }
    }

    /**
     * 跳转到之后的页面
     * @param time Long 延迟的时间
     */
    private fun toNextActivity(time: Long) {
        mNextActivityJob?.cancel()
        mNextActivityJob = launch {
            delay(time)
            LoginActivity.newInstance(this)
            finish()
        }
    }
}